package com.atguigu.tingshu.common.wxLogin;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@Slf4j
public class wxAspect {
    @Autowired
    RedisTemplate redisTemplate;

    //  利用反射机制+aop的环绕通知，实现是否需要登录功能！
@Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(wxLogin)")
    public Object wxLoginAspectAround(ProceedingJoinPoint point, wxLogin wxLogin) throws Throwable {


    //  创建一个对象

    //  如何判断一个请求是否需要登录！
    UserInfo userInfo;
    try {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");

        if (wxLogin.required()) {
            if (StringUtils.isEmpty(wxLogin)) {
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
            String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
            userInfo = (UserInfo) redisTemplate.opsForValue().get(userLoginKey);
            AuthContextHolder.setUserId(userInfo.getId());

        }
        return point.proceed();
    } catch (Throwable e) {
        throw new RuntimeException(e);
    } finally {
        AuthContextHolder.removeUserId();
    }


}
}
